import { View, Text, Image, Picker } from "@tarojs/components";
import clsx from "clsx";
import { useEffect, useRef, useState } from "react";
import ico_add_three from "@/assets/image/ico_add_three.svg";
import ico_jiantou_one from "@/assets/image/ico_jiantou_one.svg";

import "./index.scss";
import SingleAd from "./components/SingleAd";
import {
  classifyAddIndexGet,
  classifyDetail,
  classifyList,
  classifyPost,
  delAdvertisement,
} from "@/services/entities/all";
const AdManage = () => {
  const tabs = [
    { name: "首页广告", tabId: 1 },
    { name: "大类广告", tabId: 2 },
    { name: "子类广告", tabId: 3 },
  ];
  const [currentIndex, setCurrentIndex] = useState(0);

  const [adList, setAdList] = useState<any>([]);
  const [classType, setType] = useState<any>([]);
  const [childClassType, setChildClassType] = useState<any>([]);
  const [detail, setDetail] = useState<any>();
  const adListRef = useRef<any[]>([]);

  const [form, setForm] = useState({
    firstType: "",
    secondType: "",
  });

  const formChange = (key, value) => {
    const tmp = { ...form };
    tmp[key] = value;
    setForm(tmp);
  };

  const changeType = (e) => {
    const value = e.detail.value;
    formChange("firstType", value);
    setChildClassType(classType[value].list);
  };

  const getClassifyDetail = (id) => {
    classifyDetail({ id }).then((res: any) => {
      setDetail(res);
      const result =
        res.addClassifyStoreList?.map((item) => {
          return {
            ...item,
            banner: item.imageUrl?.split(","),
            isAdded: true,
          };
        }) || [];
      adListRef.current = result;
      setAdList(result);
    });
  };

  useEffect(() => {
    if (currentIndex === 1) {
      if (form.firstType) {
        getClassifyDetail(classType[form.firstType].id);
      }
    }
  }, [form.firstType, currentIndex]);

  useEffect(() => {
    if (currentIndex === 2 && form.secondType) {
      getClassifyDetail(childClassType[form.secondType].id);
    }
  }, [form.secondType, currentIndex]);

  const changeChildType = (e) => {
    const value = e.detail.value;
    formChange("secondType", value);
  };

  const onAdChange = (value, index) => {
    adListRef.current[index] = value;
    console.log(adListRef.current);
  };

  const onAdd = () => {
    if (currentIndex === 0) {
      getList();
    }
    if (currentIndex === 1) {
      console.log("adList", adListRef.current);
      classifyPost({
        ...detail,
        addClassifyStoreList: adListRef.current
          .filter((item) => {
            return item.banner && item.banner.length && item.name;
          })
          .map((item) => {
            return {
              ...item,
              imageUrl: item.banner.join(","),
            };
          }),
      }).then(() => {
        getClassifyDetail(classType[form.firstType].id);
      });
    }
    if (currentIndex === 2) {
      classifyPost({
        ...detail,
        addClassifyStoreList: adListRef.current
          .filter((item) => {
            return item.banner && item.banner.length && item.name;
          })
          .map((item) => {
            return {
              ...item,
              imageUrl: item.banner?.join(","),
            };
          }),
      }).then(() => {
        getClassifyDetail(childClassType[form.secondType].id);
      });
    }
  };

  const onDelete = (index, id, isAdded) => {
    const deleteIndex = () => {
      const temp = [...adList];
      temp.splice(index, 1);
      adListRef.current.splice(index, 1);
      setAdList(temp);
    };
    if (!isAdded) {
      deleteIndex();
      return;
    }
    if (currentIndex === 0) {
      delAdvertisement({ id }).then(() => {
        deleteIndex();
      });
    } else {
      const temp = [...adList];
      console.log("temp111", temp);
      const deleteItem: any = temp.splice(index, 1);
      console.log("temp222", temp);
      classifyPost({
        ...detail,
        addClassifyStoreList: temp.map((item) => {
          return {
            ...item,
          };
        }),
        deleteIds: deleteItem[0].id,
      });
      setAdList(temp);
    }
  };

  const addNew = () => {
    const temp = [...adList];
    const newAd = {
      orderBy: adList.length,
      banner: [],
      name: "",
      storeId: "",
      isAdded: false,
    };
    temp.push(newAd);
    adListRef.current.push(newAd);
    setAdList(temp);
  };

  const getList = () => {
    classifyAddIndexGet().then((res: any) => {
      const result = res?.map((item) => {
        return {
          ...item,
          banner: item.imageUrl?.split(","),
          isAdded: true,
        };
      });
      adListRef.current = result;
      setAdList(result);
    });
  };

  useEffect(() => {
    classifyList({}).then((res: any) => {
      setType(res);
      setChildClassType(res?.[0]?.list);
    });
  }, []);

  useEffect(() => {
    if (currentIndex === 0) {
      getList();
    } else if (currentIndex === 1) {
      if (!form.firstType) {
        setAdList([]);
      }
    } else if (currentIndex === 2) {
      if (!form.secondType) {
        setAdList([]);
      }
    }
  }, [currentIndex]);

  return (
    <View className="ad-manage-container bg-page">
      <View className="mg-lr-94 mt-48 dis-flex align-center br-32 bg-007DDB pd-4 border-box ml-12">
        {tabs?.map((item, index) => {
          return (
            <View
              onClick={() => {
                setCurrentIndex(index);
              }}
              key={index}
              className={clsx(
                "pd-tb-10 pd-lr-40 border-box br-28 fs-26 lh-36 cl-white",
                currentIndex == index ? "bg-ffffff cl-black" : ""
              )}
            >
              {item.name}
            </View>
          );
        })}
      </View>
      {(currentIndex === 1 || currentIndex === 2) && (
        <Picker
          mode="selector"
          range={classType?.map((item) => item.name)}
          onChange={changeType}
        >
          <View className="dis-flex pd-lr-26 border-box bg-ffffff mt-16">
            <View className="flex-1 fs-26 lh-32 cl-848484 pd-tb-24 border-box">
              大类名称：
            </View>
            <View className="border-bottom flex-3 fs-26 lh-32 cl-black pd-tb-24 border-box dis-flex align-center justify-between">
              <Text className="fs-24 lh-32 cl-C2C2C2">
                {form.firstType ? classType[form.firstType].name : "选择大类"}
              </Text>
              <Image src={ico_jiantou_one} className="img-32" />
            </View>
          </View>
        </Picker>
      )}
      {currentIndex === 2 && (
        <Picker
          mode="selector"
          range={childClassType?.map((item) => item.name)}
          onChange={changeChildType}
        >
          <View className="dis-flex pd-lr-26 border-box bg-ffffff mt-16">
            <View className="flex-1 fs-26 lh-32 cl-848484 pd-tb-24 border-box">
              子类名称：
            </View>
            <View className="border-bottom flex-3 fs-26 lh-32 cl-black pd-tb-24 border-box dis-flex align-center justify-between">
              <Text className="fs-24 lh-32 cl-C2C2C2">
                {form.secondType
                  ? childClassType?.[form.secondType]?.name
                  : "选择子类"}
              </Text>
              <Image src={ico_jiantou_one} className="img-32" />
            </View>
          </View>
        </Picker>
      )}
      {adList?.map((item, index) => {
        const refItem = adListRef.current[index];
        console.log("refItem", refItem);
        return (
          <SingleAd
            currentIndex={currentIndex}
            typeId={currentIndex === 1 ? form.firstType : form.secondType}
            key={`${index}_${new Date().getTime()}`}
            onDelete={() => {
              onDelete(index, item.id, item.isAdded);
            }}
            onAdd={() => {
              onAdd();
            }}
            onChange={(value) => {
              onAdChange(value, index);
            }}
            initValue={{
              banner: refItem.banner ? refItem.banner : [],
              orderBy: refItem.orderBy ?? "",
              storeId: refItem.storeId ?? "",
              name: refItem.name ?? "",
            }}
            isAdded={refItem.isAdded}
          />
        );
      })}
      <View className="bottom pd-20  dis-flex align-center border-box">
        <View
          className="flex-1 flex-center pd-tb-20 border-box bg-007DDB br-8 fs-28 lh-38 cl-white"
          onClick={addNew}
        >
          <Image src={ico_add_three} className="img-36 mr-8" />
          <Text>新增</Text>
        </View>
      </View>
    </View>
  );
};

export default AdManage;
